<template>
  <el-dialog
      fullscreen
      top="5vh"
      width="1400px"
      title="SKU管理"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <div class="sku-container">
      <div class="product-info">
        <h3>{{ currentProduct.name }}</h3>
        <p>商品ID: {{ currentProduct.id }}</p>
      </div>

      <!-- 规格配置区域 -->
      <el-card class="spec-config" shadow="never">
        <div slot="header" class="clearfix">
          <span>规格配置</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="onAddSpec">添加规格</el-button>
        </div>

        <div class="spec-list">
          <div v-for="(spec, specIndex) in specList" :key="spec.id" class="spec-item">
            <div class="spec-header">
              <el-input
                v-model="spec.spec_name"
                placeholder="规格名称，如：颜色、尺寸"
                style="width: 200px; margin-right: 10px;"
              />
              <el-button type="text" @click="addSpecValue(specIndex)">添加规格值</el-button>
              <el-button type="text" style="color: #F82222" @click="removeSpec(specIndex)">删除规格</el-button>
            </div>
            <div class="spec-values">
              <el-tag
                v-for="(value, valueIndex) in spec.spec_values"
                :key="valueIndex"
                closable
                @close="removeSpecValue(specIndex, valueIndex)"
                style="margin-right: 10px; margin-bottom: 10px;"
              >
                {{ value }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="spec-actions" v-if="specList.length > 0">
          <el-button type="primary" @click="saveSpecs">保存规格配置</el-button>
          <el-button @click="generateSkuCombinations">生成SKU组合</el-button>
        </div>
      </el-card>

      <!-- SKU管理区域 -->
      <el-card class="sku-manager" shadow="never">
        <div slot="header" class="clearfix">
          <span>SKU管理</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="onAddSku">新增SKU</el-button>
        </div>

        <div class="sku-table">
          <el-table
              size="large"
              stripe
              border
              v-loading="loading"
              :data="skuList"
              row-key="id"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.8)"
          >
            
            <el-table-column prop="sku_code" label="SKU编码" width="150"/>
            <el-table-column prop="image" label="SKU图片" width="120">
              <template slot-scope="scope">
                <el-image
                    v-if="scope.row.image"
                    :preview-src-list="[scope.row.image]"
                    style="width: 80px; height: 80px"
                    :src="scope.row.image" fit="contain">
                  <template #error>
                    <img src="@/assets/file.png" alt="" style="width: 80px; height: 80px">
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="spec_combination" label="规格组合" min-width="200">
              <template slot-scope="scope">
                <div v-if="scope.row.spec_combination">
                  <el-tag
                    v-for="(value, key) in JSON.parse(scope.row.spec_combination)"
                    :key="key"
                    size="mini"
                    style="margin-right: 5px; margin-bottom: 5px;"
                  >
                    {{ key }}: {{ value }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="original_price" label="原价" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.original_price }}
              </template>
            </el-table-column>
            <el-table-column prop="share_price" label="分销价" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.share_price }}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="80"/>
            <el-table-column prop="unit" label="单位" width="80"/>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
                <el-tag v-else type="info">禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
              <template slot-scope="scope">
                <el-button type="text" @click="onEditSku(scope.row)">编辑</el-button>
                <el-button type="text" style="color: #F82222" @click="onDeleteSku(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 规格值输入弹窗 -->
    <el-dialog
        title="添加规格值"
        :visible.sync="specValueDialog"
        width="400px"
        append-to-body
    >
      <el-input
        v-model="newSpecValue"
        placeholder="请输入规格值"
        @keyup.enter.native="confirmAddSpecValue"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="specValueDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAddSpecValue">确定</el-button>
      </div>
    </el-dialog>

    <!-- SKU添加/编辑弹窗 -->
    <el-dialog
        top="10vh"
        width="800px"
        title="添加/编辑SKU"
        :visible.sync="skuDialogValue"
        :close-on-click-modal="false"
        append-to-body
    >
      <SubmitForm
          :rule-form="skuForm"
          :rules="skuRules"
          :form-list="skuFormList"
          @change="handleSkuFormChange"
          @save="onSaveSku"
          @close="skuDialogValue = false"
      >
        <!-- 自定义规格选择组件 -->
        <template slot="spec_combination">
          <SpecCombinationSelector
            ref="specSelector"
            v-model="skuForm.spec_combination"
            :spec-list="specList"
            @change="handleSpecCombinationChange"
          />
        </template>
      </SubmitForm>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {http} from '@/api'
import SpecCombinationSelector from '@/components/SpecCombinationSelector.vue'

export default {
  name: 'SkuManager',
  components: {
    SpecCombinationSelector
  },
  data() {
    return {
      dialogValue: false,
      skuDialogValue: false,
      specValueDialog: false,
      loading: false,
      currentProduct: {},
      skuList: [],
      specList: [],
      skuForm: {},
      newSpecValue: '',
      currentSpecIndex: -1,
      defaultSkuForm: {
        product_id: '',
        sku_code: '',
        spec_combination: '{}',
        price: 0,
        original_price: 0,
        share_price: 0,
        stock: 0,
        image: '',
        unit: '',
        status: 1
      },
      skuRules: {
        sku_code: [{required: true, message: 'SKU编码不能为空'}],
        price: [{required: true, message: '价格不能为空'}],
      },
      skuFormList: [
        {
          label: 'SKU编码',
          prop: 'sku_code',
          name: 'input',
          colSpan: 12,
          placeholder: '请输入SKU编码'
        },
        {
          label: 'SKU图片',
          prop: 'image',
          name: 'file',
          colSpan: 12
        },
        {
          label: '规格组合',
          prop: 'spec_combination',
          slot: true,
          colSpan: 24
        },
        {
          label: '价格',
          prop: 'price',
          name: 'number',
          colSpan: 8,
          min: 0,
          precision: 2,
          step: 0.01
        },
        {
          label: '原价',
          prop: 'original_price',
          name: 'number',
          colSpan: 8,
          min: 0,
          precision: 2,
          step: 0.01
        },
        {
          label: '分销价',
          prop: 'share_price',
          name: 'number',
          colSpan: 8,
          min: 0,
          precision: 2,
          step: 0.01
        },
        {
          label: '库存',
          prop: 'stock',
          name: 'number',
          colSpan: 12,
          min: 0
        },
        {
          label: '单位',
          prop: 'unit',
          name: 'input',
          colSpan: 12,
          placeholder: '如：人、天、次'
        },
        {
          label: '状态',
          prop: 'status',
          name: 'switch',
          colSpan: 24,
          activeValue: 1,
          inactiveValue: 0,
          activeText: '启用',
          inactiveText: '禁用'
        },
      ]
    }
  },
  methods: {
    open(product) {
      this.currentProduct = product;
      this.dialogValue = true;
      this.loadSpecList();
      this.loadSkuList();
    },

    // 加载规格列表
    loadSpecList() {
      http.productSpec.list({ product_id: this.currentProduct.id }).then(res => {
        this.specList = res.data.map(spec => ({
          ...spec,
          spec_values: spec.spec_values ? JSON.parse(spec.spec_values) : []
        }));
      }).catch(() => {
        this.specList = [];
      });
    },

    // 加载SKU列表
    loadSkuList() {
      this.loading = true;
      http.productSku.list({ product_id: this.currentProduct.id }).then(res => {
        this.skuList = res.data;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    // 添加规格
    onAddSpec() {
      this.specList.push({
        product_id: this.currentProduct.id,
        spec_name: '',
        spec_values: [],
        sort: this.specList.length,
        status: 1
      });
    },

    // 删除规格
    removeSpec(index) {
      this.specList.splice(index, 1);
    },

    // 添加规格值
    addSpecValue(specIndex) {
      this.currentSpecIndex = specIndex;
      this.newSpecValue = '';
      this.specValueDialog = true;
    },

    // 确认添加规格值
    confirmAddSpecValue() {
      if (this.newSpecValue.trim()) {
        this.specList[this.currentSpecIndex].spec_values.push(this.newSpecValue.trim());
        this.specValueDialog = false;
      }
    },

    // 删除规格值
    removeSpecValue(specIndex, valueIndex) {
      this.specList[specIndex].spec_values.splice(valueIndex, 1);
    },

    // 保存规格配置
    saveSpecs() {
      const specsToSave = this.specList.filter(spec => spec.spec_name.trim());

      if (specsToSave.length === 0) {
        this.$message.warning('请至少添加一个规格');
        return;
      }

      const promises = specsToSave.map(spec => {
        const specData = {
          ...spec,
          spec_values: JSON.stringify(spec.spec_values)
        };

        if (spec.id) {
          return http.productSpec.update(spec.id, specData);
        } else {
          return http.productSpec.create(null, specData);
        }
      });

      Promise.all(promises).then(() => {
        this.$message.success('规格配置保存成功');
        this.loadSpecList();
      })
    },

    // 生成SKU组合
    generateSkuCombinations() {
      const validSpecs = this.specList.filter(spec => spec.spec_name.trim() && spec.spec_values.length > 0);

      if (validSpecs.length === 0) {
        this.$message.warning('请先配置规格');
        return;
      }

      // 调用后端接口生成SKU组合
      http.productSku.generate({ product_id: this.currentProduct.id }).then(res => {
        this.$message.success(res.data.message);
        this.loadSkuList();
      })
    },

    // 生成规格组合
    generateCombinations(specs) {
      const result = [];

      const generate = (current, index) => {
        if (index === specs.length) {
          result.push([...current]);
          return;
        }

        for (const value of specs[index].spec_values) {
          current[index] = value;
          generate(current, index + 1);
        }
      };

      generate(new Array(specs.length), 0);
      return result;
    },

    // 生成SKU编码
    generateSkuCode(combination) {
      return `${this.currentProduct.id}_${combination.join('_')}`;
    },

    onAddSku() {
      this.skuForm = {
        ...this.defaultSkuForm,
        product_id: this.currentProduct.id
      };
      // 更新规格组合选择器的规格列表
      this.updateSpecCombinationProps();
      this.skuDialogValue = true;
    },

    onEditSku(row) {
      this.skuForm = { ...row };
      console.log('编辑SKU，规格组合:', this.skuForm.spec_combination);
      // 更新规格组合选择器的规格列表
      this.updateSpecCombinationProps();
      this.skuDialogValue = true;

      // 确保组件有时间响应数据变化
      this.$nextTick(() => {
        console.log('SKU表单已设置，当前规格组合:', this.skuForm.spec_combination);
      });
    },

    onDeleteSku(row) {
      this.$confirm('确定要删除这个SKU吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.productSku.delete(row.id).then(() => {
          this.$message.success('删除成功');
          this.loadSkuList();
        });
      });
    },

    handleSkuFormChange({key, val}) {
      // 处理SKU表单变化
    },

    updateSpecCombinationProps() {
      // 规格列表已经在data中，不需要额外更新
      // 这个方法保留用于将来可能的扩展
    },

    handleSpecCombinationChange(combination) {
      // 处理规格组合变化
      console.log('规格组合变化:', combination);
    },

        onSaveSku() {
      // 验证规格组合JSON格式
      try {
        if (this.skuForm.spec_combination) {
          const parsed = JSON.parse(this.skuForm.spec_combination);
          // 检查是否选择了规格
          if (Object.keys(parsed).length === 0) {
            this.$message.warning('请选择规格组合');
            return;
          }
        }
      } catch (e) {
        this.$message.error('规格组合JSON格式不正确');
        return;
      }

      http.productSku[this.skuForm.id ? 'update' : 'create'](this.skuForm.id, this.skuForm).then(res => {
        this.$message.success('操作成功');
        this.skuDialogValue = false;
        this.loadSkuList();
      });
    }
  }
}
</script>

<style scoped lang="scss">
.sku-container {
  .product-info {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;

    h3 {
      margin: 0 0 10px 0;
      color: #303133;
    }

    p {
      margin: 0;
      color: #606266;
    }
  }

  .spec-config {
    margin-bottom: 20px;

    .spec-list {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      .spec-item {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;

        .spec-header {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
        }

        .spec-values {
          min-height: 40px;
        }
      }
    }

    .spec-actions {
      margin-top: 20px;
      text-align: center;
    }
  }

  .sku-manager {
    .sku-table {
      max-height: 400px;
      overflow-y: auto;
    }
  }
}
</style>
